package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.PageUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.utils.Constants;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.codehaus.jettison.util.FastStack;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SmallVideosService {
    @Autowired
    private OssTemplate ossTemplate;
    @Autowired
    private FastFileStorageClient fastFileStorageClient;
    @Autowired
    private FdfsWebServer webServer;
    @Autowired
    private RedisTemplate<String ,String> redisTemplate;
    @DubboReference
    private VideoApi videoApi;
    @DubboReference
    private UserInfoApi userInfoApi;
    @CacheEvict(value="videos",allEntries = true)
    public void saveVideos(MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {
           if (videoThumbnail.isEmpty()||videoFile.isEmpty()){
               throw  new BusinessException(ErrorResult.error());
           }
        String filename = videoFile.getOriginalFilename();
       filename = filename.substring(filename.lastIndexOf(".") + 1);
        StorePath storePath = fastFileStorageClient.uploadFile(videoFile.getInputStream(), videoFile.getSize(), filename, null);
        String videoFileurl = webServer.getWebServerUrl() + storePath.getFullPath();
        String ossurl = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());
        Video video = new Video();
        video.setUserId(UserHolder.getUserId());
        video.setVideoUrl(videoFileurl);
        video.setPicUrl(ossurl);
        video.setText("test");
       String videoid =  videoApi.save(video);
       if (StringUtils.isEmpty(videoid)) {
           throw new BusinessException(ErrorResult.error());
       }
    }
    @Cacheable(
            value="videos",
            key = "T(com.tanhua.server.interceptor.UserHolder).getUserId()+'_'+#page+'_'+#pagesize")
    public PageResult getall(Integer page, Integer pagesize) {
         String key = Constants.VIDEOS_RECOMMEND+UserHolder.getUserId();
        String redskey = redisTemplate.opsForValue().get(key);
        List<Video> list = new ArrayList<>();
        int redisPages = 0;
             if (!StringUtils.isEmpty(redskey)){
                 String[] ids = redskey.split(",");
                 if ((page-1)*pagesize<ids.length){
                     List<Long> vids = Arrays.stream(ids).skip((page - 1) * pagesize).limit(pagesize).map(e -> Long.valueOf(e))
                             .collect(Collectors.toList());
                     list = videoApi.findMovementsByVids(vids);
                 }
                 redisPages = PageUtil.totalPage(ids.length,pagesize);
             }
             if (list.isEmpty()){
                 list = videoApi.queryVideoList(page - redisPages, pagesize);
             }
        List<Long> userId = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findbyIds(userId, null);
        List<VideoVo> videoVoList = new ArrayList<>();
        for (Video video : list) {
            UserInfo userInfo = map.get(video.getUserId());
            if (userInfo!=null){
                VideoVo init = VideoVo.init(userInfo, video);
                videoVoList.add(init);
            }
        }
        return new PageResult(page,pagesize,0l,videoVoList);
    }
}
